package com.hk.service.impl;

import com.hk.dao.NewsTypeDao;
import com.hk.model.Document;
import com.hk.model.NewsType;
import com.hk.service.INewsTypeService;
import com.hk.utils.Io;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/19 17:14
 * State：新闻类型业务逻辑层
 */
public class NewsTypeServiceImpl implements INewsTypeService {

    List<NewsType> newsTypes = null;

    @Override
    public List<NewsType> findAllNewsType(String path) {
        NewsTypeDao newsTypeDao = new NewsTypeDao();
        newsTypes = newsTypeDao.findAllNewsType();
//      1、存储路径  2、文件夹 3、文件
        Document document = new Document(path,"NewsType", "NewsType.txt");
        writeData(newsTypes,document);
        if (newsTypes == null && newsTypes.isEmpty()) {
            System.out.println("未获取到新闻类型数据");
            return null;
        }
        return newsTypes;

    }

    /**
     * 读取数据
     * @param document
     * @return
     */
    @Override
    public List<?> readData(Document document) {
        //    根据该对象内多少属性进行转化划分
        final int count = 3;
        newsTypes = new ArrayList<>();
        List<String> list = Io.readData(document);
        for (int i = 0; i < list.size(); i=i+count ) {
            NewsType newsType = new NewsType(
                Integer.parseInt(list.get(i)),
                list.get(i+1),
                list.get(i+2)
            );
            newsTypes.add(newsType);
        }
        return newsTypes;
    }

    /**
     * 写入数据
     * @param list
     * @param document
     */
    @Override
    public void writeData(List<?> list, Document document) {
        newsTypes = (List<NewsType>) list;
        List<String> list1 = new ArrayList<>();
        for (NewsType newsType : newsTypes) {
            list1.add(String.valueOf(newsType.getTypeId()));
            list1.add(newsType.getTypeName());
            list1.add(newsType.getTypeUrl());
        }
        Io.writeData(list1,document);
    }
}
